package com.ld.hpfs.web.controller;

import java.io.PrintWriter;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.ld.hpfs.common.jackson.JackJson;
import com.ld.hpfs.common.utils.Const;
import com.ld.hpfs.common.utils.GmailSender;
import com.ld.hpfs.common.utils.GmailSenderInfo;
import com.ld.hpfs.common.utils.MailSenderInfo;
import com.ld.hpfs.common.utils.SimpleMailSender;
import com.ld.hpfs.common.utils.Tools;
import com.ld.hpfs.pojo.ExtPager;
import com.ld.hpfs.pojo.User;
import com.ld.hpfs.service.DealAbandonService;
import com.ld.hpfs.service.DealSendMsgService;
import com.ld.hpfs.web.interseptor.WebConstants;

@Controller
public class DealAbandonController {
	private static final Logger logger = LoggerFactory
			.getLogger(DealController.class);
	@Autowired
	private DealAbandonService dealAbandonService;
	@Autowired
	private DealSendMsgService dealsendmsgservice;
	@Autowired
	private JdbcTemplate jdbcTemplate;
	// 邮箱端口全局变量
	private String port;

	/* 保存红废票的录入信息 */
	@RequestMapping(value = "/dealAbandon", method = RequestMethod.POST)
	public void dealAbandon(ExtPager page, HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		String resultMsg = "";// 用于返回的结果
		HashMap<String, Object> param = new HashMap<String, Object>();

		try {
			String date = Tools.date2Str(new Date());// 获得当前日期
			String cpnId = session.getAttribute(WebConstants.CURRENT_COMPANY).toString();
			User user = (User) session.getAttribute(WebConstants.CURRENT_USER);// 得到当前用户
			if (user != null) {
				String userName = user.getAccount();// 获得当前用户名称
				String userId = user.getUserId();// 获得当前用户的id号
				/* 获得前台传递参数 */
				// 红废票id
				String voided_doc_id = request.getParameter("voided_doc_id");
				// 原发票代码
				String num = request.getParameter("num") == null ? null
						: (String) request.getParameter("num");
				// 原发票开始号
				String numStart = request.getParameter("numStart") == null ? null
						: (String) request.getParameter("numStart");
				// 原发票结束号
				String numEnd = request.getParameter("numEnd") == null ? null
						: (String) request.getParameter("numEnd");
				// 原开票日期
				String startDate = request.getParameter("startDate") == "" ? null
						: (String) request.getParameter("startDate");
				// 退回日期
				String backDate = request.getParameter("backDate") == "" ? null
						: (String) request.getParameter("backDate");
				// 标记状态：作废 红冲
				String type = request.getParameter("type") == null ? null
						: (String) request.getParameter("type");
				
				
				/* start红票信息 */
				// 红票代码
				String redCode = request.getParameter("redCode") == null ? null
						: (String) request.getParameter("redCode");
				// 红票号码
				String redNum = request.getParameter("redNum") == null ? null
						: (String) request.getParameter("redNum");
				// 红票日期
				String redDate = request.getParameter("redDate") == "" ? null
						: (String) request.getParameter("redDate");
				// 红票金额
				String redAmount = request.getParameter("redAmount") == "" ? null
						: (String) request.getParameter("redAmount");
				// 红字通知单号码
				String redNotice = request.getParameter("redNotice") == "" ? null
						: (String) request.getParameter("redNotice");
				/* end红票信息 */
				// 备注
				String note = request.getParameter("note") == null ? null
						: (String) request.getParameter("note");

				/* 单据信息 */
				// 单据号
				String docNo = request.getParameter("docNo") == null ? null
						: (String) request.getParameter("docNo");
				// 客户名称
				String custName = request.getParameter("custName") == null ? null
						: (String) request.getParameter("custName");
				String custCode = request.getParameter("custCode") == null ? null
                            : (String) request.getParameter("custCode"); 
				int editflag = Integer.parseInt(request.getParameter("update"));
				int resubmit = Integer.parseInt(request.getParameter("submit"));
				
				// 原发票价税合计
				String curTotal =request.getParameter("curTotal") == null ? null
						: (String) request.getParameter("curTotal"); 
				if (curTotal == "" || curTotal == null) {
					curTotal = "0";
				}
				// 发票类型
				String docType = request.getParameter("docType") == null ? null
						: (String) request.getParameter("docType");
				if (docType.equals("增值税专用发票")) {
					docType = "VAT";
				} else if (docType.equals("增值税普通发票")) {
					docType = "N_VAT";
				} else if (docType.equals("营业税发票")) {
					docType = "BT";
				} else if (docType.equals("出口发票")) {
					docType = "E_INV";
				} else if (docType.equals("交通运输发票")) {
					docType = "T_INV";
				} else
					docType = null;
				if(docNo.equals("--")){
					docNo=null;
				}
				if(curTotal.equals("--")){
					curTotal=null;
				}
				if(custName.equals("  --")){
					custName=null;
				}
				param.put("companyId", cpnId);

				param.put("userName", userName);
				param.put("userId", userId);
				param.put("date", date);

				param.put("voided_doc_id", voided_doc_id);
				param.put("num", num);
				param.put("numStart", numStart);
				param.put("numEnd", numEnd);
				param.put("startDate", startDate);
				param.put("backDate", backDate);
				param.put("type", type);

				param.put("redCode", redCode);
				param.put("redNum", redNum);
				param.put("redDate", redDate);
				param.put("redAmount", redAmount);
				param.put("redNotice", redNotice);

				param.put("remark", note);

				param.put("docNo", docNo);
				param.put("custName", custName);
				param.put("custCode", custCode); 
				param.put("curTotal", curTotal);
				param.put("docType", docType);
				// 更新update_id,update_name信息 by guxiaoli
				param.put("update_id", Integer.parseInt(user.getUserId()));
				param.put("update_name", user.getAccount());

				// 红废审核状态
				param.put("status", 1);
				Integer invoice_id=null;
				boolean isSend = false;
				// 重新提交
				if (resubmit == 1) {
					// 先删除票据
					dealAbandonService.infoDelete(param);
					// 保存用户输入的红废记录信息
					dealAbandonService.dealAbandonInfoSave(param);
					List<HashMap<String, Object>> invoide=dealAbandonService.getInoviceIdEnd();
					  invoice_id=(Integer) invoide.get(0).get("voided_doc_id");
					isSend = true;
				} else {
					// 编辑
					if (editflag == 1) {
						dealAbandonService.dealAbandonUpdate(param);
						 invoice_id=Integer.parseInt(voided_doc_id);	
					} 
					// 新建
					else {
						// 检查此票据是否已被申请
						List<HashMap<String, Object>> list = dealAbandonService.getInfo(param);
						if (list != null && !list.isEmpty()) {
							dealAbandonService.dealAbandonInfoSave(param);
							//获取新插入进来的invoice_id
							List<HashMap<String, Object>> invoide=dealAbandonService.getInoviceIdEnd();
							  invoice_id=(Integer) invoide.get(0).get("voided_doc_id");
							isSend = true;	
					}else {
							dealAbandonService.dealAbandonInfoSave(param);// 保存用户输入的红废记录信息
							//获取新插入进来的invoice_id
							List<HashMap<String, Object>> invoide=dealAbandonService.getInoviceIdEnd();
							  invoice_id=(Integer) invoide.get(0).get("voided_doc_id");
							isSend = true;
						}
					}
				}
				 HashMap<String, Object> docStatue = new HashMap<String, Object>();
				docStatue.put("company_id", cpnId);
				docStatue.put("docNo", docNo);
				docStatue.put("invoice_id", invoice_id);
				HashMap<String, Object> statue = dealAbandonService.getInvoiceStatus(docStatue);
				// 如果是通过 状态 ，则执行存储过程
				if ("3".equals(statue.get("statusNo").toString())) {
					HashMap<String, Object> execSpParam = new HashMap<String, Object>();
					execSpParam.put("docNo", docNo);
					execSpParam.put("userId", user.getUserId());
					execSpParam.put("companyId", cpnId);
					execSpParam.put("invoiceId", invoice_id);
					execSp(execSpParam);
				}
				// 当为修改时不进行发信息和执行存储过程操作
				if (isSend) {
					// 取得是否启用邮件通知
					HashMap<String, Object> modelparam = new HashMap<String, Object>();
					modelparam.put("model", 3);
					// model2 : 红废审核者模板
					ArrayList<HashMap<String, Object>> model3 = dealsendmsgservice.getMsgForPreview(modelparam);
					int useFlag = 0;
					// 检查是否设置了审核者模板
					if (model3.size() != 0) {
						useFlag = Integer.parseInt(model3.get(0).get("useFlag").toString());
					}
					// 当状态为2，3是即只启用邮件或两个都启用
					if (useFlag == 2 || useFlag == 3) {
						// 发送邮件操作
						try {
							// 得到所有一级审核者，加当前公司限制
							ArrayList<HashMap<String, Object>> checkLevel1 = dealAbandonService.getCheckLevel1(cpnId);
							// 得到所有二级审核者，加当前公司限制
							ArrayList<HashMap<String, Object>> checkLevel2 = dealAbandonService.getCheckLevel2(cpnId);
							String status = statue.get("statusNo").toString();
							
							HashMap<String, Object> getMailInfo = new HashMap<String, Object>();
							
							MailSenderInfo mailInfo = new MailSenderInfo();
							String reviewTo = model3.get(0).get("review_to").toString();
							String reviewCc = model3.get(0).get("review_cc").toString();
							String reviewBcc = model3.get(0).get("review_bcc").toString();
							if (!Tools.isEmpty(reviewTo)) {
								if(status.equals("1")) {
									// 给审核者发邮件
									try {
										sendCheckerMail(reviewTo, reviewCc, reviewBcc, checkLevel1, statue, model3);
									} catch (Exception e) {
										System.out.println(e);
									}
								} 
								// 当此票据为等待二级审核 
								else if (status.equals("2")) {
									// 给审核者发邮件
									if (checkLevel2.size() != 0) {
										try {
											sendCheckerMail(reviewTo, reviewCc, reviewBcc, checkLevel2, statue, model3);
										} catch (Exception e) {
											System.out.println(e);
										}
									}
								} 
								// 此红废票无审核直接通过审核者模板收件人设置为固定邮箱的发信给固定收件人
								else if (status.equals("3")) {
									String review_to = model3.get(0).get("review_to").toString();
									String review_cc = model3.get(0).get("review_cc").toString();
									String review_bcc = model3.get(0).get("review_bcc").toString();
									if (!Tools.isEmpty(review_to) && review_to.contains("@")) {
										getMailInfo = getMailMethord(statue, null, model3);
										
										mailInfo = (MailSenderInfo) getMailInfo.get("mailInfo");
										sendMail(review_to, mailInfo);
									}
									if (!Tools.isEmpty(review_cc) && review_cc.contains("@")) {
										getMailInfo = getMailMethord(statue, null, model3);
										
										mailInfo = (MailSenderInfo) getMailInfo.get("mailInfo");
										sendMail(review_cc, mailInfo);
									}
									if (!Tools.isEmpty(review_bcc) && review_bcc.contains("@")) {
										getMailInfo = getMailMethord(statue, null, model3);
										
										mailInfo = (MailSenderInfo) getMailInfo.get("mailInfo");
										sendMail(review_bcc, mailInfo);
									}
								}
							}
						} catch (Exception e) {
							System.out.println(e);
						}
					}
				}
//				// 这里作废操作应改至审核通过后
//				 dealAbandonService.docTypeUpdate(param);//更新head表中该条信息记录状态为"作废"以"作废方式"

				resultMsg = "1";
				writer.print(resultMsg);
			} else {
				writer.print("");
			}
		} catch (Exception e) {
			logger.error("Exception: ", e);
			resultMsg = "2";
			writer.print(resultMsg);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	// 获得修改人的信息
	@RequestMapping(value = "/getdealAbandonList", method = RequestMethod.POST)
	public void getdealAbandonList(ExtPager page, HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");

		HashMap<String, Object> param = new HashMap<String, Object>();// 用于向后台传递参数
		HashMap<String, Object> result = new HashMap<String, Object>();// 用于返回的结果集
		String companyId = session.getAttribute(WebConstants.CURRENT_COMPANY).toString();
		int state=0;
		// 审核状态
		String StateSearch = request.getParameter("state");
		// 作废状态
		String VOID_FLAG = request.getParameter("invalid");
		// 折线图钻取年、月
		String year = request.getParameter("year");
		String month = request.getParameter("month");
		
		/* 得到一个或多个单据号 */
		String miutinum = request.getParameter("nums");
		// 单据号的开始和结束范围 
		String DOCUMENT_NO_First = request.getParameter("startnum");
		String DOCUMENT_NO_End = request.getParameter("endnum");
		// 客户名称 
		String CUST_NAME_CHN = request.getParameter("custname");
		// 原开票日期开始 
		String INVOICE_DATE_START = request.getParameter("startday");
		// 原开票日期结束 
		String INVOICE_DATE_END = request.getParameter("endday");
		// 发票代码 
		String INVOICE_CODE = request.getParameter("code");
		// 发票开始号 
		String INVOICE_NO_BEGIN = request.getParameter("sno");
		// 发票结束号 
		String INVOICE_NO_END = request.getParameter("eno");
		// 退回开始日期 
		String RETURN_DATE_START = request.getParameter("return_sday");
		// 退回开始日期 
		String RETURN_DATE_END = request.getParameter("return_eday");

		param.put("MONTH", month);
		param.put("YEAR", year);
		param.put("VOID_FLAG", VOID_FLAG);
		
		if(StateSearch!=null && StateSearch.equals("2")){
			param.put("StateSearch", 2);
		}
		if(StateSearch!=null && StateSearch.equals("1")){
			param.put("StateSearch", 1);
		}
		if(StateSearch!=null && StateSearch.equals("3")){
			param.put("StateSearch", 3);
		}
		
		param.put("DOCUMENT_NO_First", DOCUMENT_NO_First);
		param.put("DOCUMENT_NO_End", DOCUMENT_NO_End);
		param.put("miutinum", miutinum);
		
		param.put("CUST_NAME_CHN", CUST_NAME_CHN);

		param.put("INVOICE_DATE_START", INVOICE_DATE_START);
		param.put("INVOICE_DATE_END", INVOICE_DATE_END);

		param.put("INVOICE_CODE", INVOICE_CODE);

		param.put("INVOICE_NO_BEGIN", INVOICE_NO_BEGIN);
		param.put("INVOICE_NO_END", INVOICE_NO_END);

		param.put("RETURN_DATE_START", RETURN_DATE_START);
		param.put("RETURN_DATE_END", RETURN_DATE_END);
		
		param.put("companyId", companyId);
		try {
			User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
			if (user != null) {
				// 设置显示在前台的数据范围
				param.put("pageStart", page.getStart());
				param.put("pageEnd", page.getStart() + page.getLimit());
				//根据userId判断是否是超级管理员或系统管理员
				HashMap<String, Object> userId = new HashMap<String, Object>();
				userId.put("userId", Integer.parseInt(user.getUserId()));
				List<HashMap<String, Object>> role = dealAbandonService.getRoleById(userId);
				boolean rloes=false;
				for (int i = 0; i < role.size(); i++) {
					if (role.get(i).get("roleName").equals("系统管理员") || role.get(i).get("roleName").equals("超级管理员")) {
						rloes=true;
						break;
					}
					}
				if (rloes) {
					param.put("role","ok");
				}else{
					param.put("role",null);
				}
				param.put("userId", Integer.parseInt(user.getUserId()));
				String language = (String) session.getAttribute(WebConstants.CURRENT_LANG);
				param.put("language", language);
				// 获得要显示的数据
				List<HashMap<String, Object>> list = dealAbandonService.getdealAbandonList(param);

				logger.debug("{}", list);
				if (list != null && list.size() > 0) {// 准备前台所需的各种数据
					result.put("success", true);
					result.put("total", param.get("pageCount"));
					result.put("data", list);
				} else {
					result.put("success", true);
					result.put("total", param.get("pageCount"));
					result.put("data", "");
				}

				String returnMsg = JackJson.fromObjectToJson(result);
				logger.debug("{}", returnMsg);
				writer.print(returnMsg);// 传到前台显示
			} else {
				writer.print("");
			}
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	// 验证红废票据信息
	@RequestMapping(value = "/testdealAbandonInfo", method = RequestMethod.POST)
	public void testdealAbandonInfo(ExtPager page, HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		try {
			HashMap<String, Object> param = new HashMap<String, Object>();// 用于向后台传递参数
			HashMap<String, Object> result = new HashMap<String, Object>();// 用于返回的结果集
			User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
			if (user != null) {
				param.put("companyId",
						session.getAttribute(WebConstants.CURRENT_COMPANY)
								.toString());
				// 原发票代码
				String num = request.getParameter("num") == null ? null
						: (String) request.getParameter("num");
				// 原发票开始号
				String numStart = request.getParameter("numStart") == null ? null
						: (String) request.getParameter("numStart");
				// 原发票结束号
				String numEnd = request.getParameter("numEnd") == null ? null
						: (String) request.getParameter("numEnd");
				
				// 语言
				String language = (String) session
						.getAttribute(WebConstants.CURRENT_LANG);
				param.put("language", language);
				param.put("num", num);
				param.put("numStart", numStart);
				param.put("numEnd", numEnd);
				List<HashMap<String, Object>> listInfo = dealAbandonService
						.getTestInfo(param);// 根据参数获得所需数据库数据
				if (listInfo != null && !listInfo.isEmpty()) {
					HashMap<String, Object> map = listInfo.get(0);
					if (map != null && map.size() > 0) {// 准备前台所需的各种数据
						result.put("data", map);
						result.put("result", 1);
					}
				} else {
					result.put("data", "");
					result.put("result", 2);

				}
				String returnMsg = JackJson.fromObjectToJson(result);
				logger.debug("{}", returnMsg);
				writer.print(returnMsg);// 传到前台显示
			} else {
				writer.print("");
			}
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}
	
	// 取得发票号码区间合计金额
	@RequestMapping(value = "/getAbandonCount", method = RequestMethod.POST)
	public void getAbandonCount(HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		HashMap<String, Object> param = new HashMap<String, Object>();
		HashMap<String, Object> result = new HashMap<String, Object>();
		try {
			User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
			String companyId = session.getAttribute(WebConstants.CURRENT_COMPANY).toString();
			if (user != null) {
				// 原发票开始号
				String numStart = request.getParameter("numStart");
				// 原发票结束号
				String numEnd = request.getParameter("numEnd");
				param.put("companyId", companyId);
				param.put("numStart", numStart);
				param.put("numEnd", numEnd);
				HashMap<String, Object> abandonCount = dealAbandonService.getAbandonCount(param);// 根据参数获得所需数据库数据
				// 取得结果集中合计金额
				String amount = abandonCount.get("amount").toString();
				result.put("amount", amount);
				String returnMsg = JackJson.fromObjectToJson(result);
				logger.debug("{}", returnMsg);
				writer.print(returnMsg);
			} else {
				writer.print("");
			}
		} catch (Exception e) {
			logger.error("Exception: ", e);
			result.put("amount", "");
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	// 删除红废记录
	@RequestMapping(value = "/dealabandonDel", method = RequestMethod.POST)
	public void dealabandonDel(ExtPager page, HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		HashMap<String, Object> param = new HashMap<String, Object>();// 用于向后台传递参数
		HashMap<String, Object> result = new HashMap<String, Object>();// 用于返回的结果集
		User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
		try {
			if (user != null) {
				param.put("companyId",
						session.getAttribute(WebConstants.CURRENT_COMPANY)
								.toString());
				// 原发票代码
				String ids = request.getParameter("ids") == null ? null
						: (String) request.getParameter("ids");
				// 红废票的主键
				 String VOIDED_DOC_ID=
			 request.getParameter("VOIDED_DOC_ID") == null ? null
				 : (String)request.getParameter("VOIDED_DOC_ID");
				 param.put("VOIDED_DOC_ID", VOIDED_DOC_ID);
				if (VOIDED_DOC_ID != null && VOIDED_DOC_ID != "") {
					List<HashMap<String, String>> lists = new ArrayList<HashMap<String, String>>();
					String[] idnums = VOIDED_DOC_ID.split(",");
					HashMap<String, String> map = new HashMap<String, String>();
					for (int i = 0; i < idnums.length; i++) {
						map = new HashMap<String, String>();
						map.put("id", idnums[i]);
						lists.add(map);
					}
					param.put("DocList", lists);
				} else {
					param.put("DocList", null);
				}

				// if(VOIDED_DOC_ID!=null && VOIDED_DOC_ID !=""){
				// List<HashMap<String,String>> lists = new
				// ArrayList<HashMap<String,String>>();
				// String[] idnums = VOIDED_DOC_ID.split(",");
				// HashMap<String,String> map= new HashMap<String,String>();
				// for(int i=0;i<idnums.length;i++){
				// map = new HashMap<String,String>();
				// map.put("id", idnums[i]);
				// lists.add(map);
				// }
				// param.put("IDList", lists);
				// }else{
				// param.put("IDList", null);
				// }
				// 回来接着写.......
				/*
				 * 要求： 1.得到红废表里面的发票号码，代码，日期 2.把这些号码，代码，日期更新到单据主表之中
				 */
				List<HashMap<String, Object>> InvoiceList = dealAbandonService
						.getInvoiceInfo(param);// 根据单据号得到发票号码,代码,日期
				param.put("InvoiceList", InvoiceList);
				// 更新update_id,update_name信息 by guxiaoli
				param.put("update_id", Integer.parseInt(user.getUserId()));
				param.put("update_name", user.getAccount());
				for (int i = 0; i < InvoiceList.size(); i++) {
					if (Integer.parseInt(InvoiceList.get(i).get("VOID_FLAG").toString())<10) {
						dealAbandonService.updateInvoiceInfo(param);// 将得到的发票代码,号码,等更新到单据主表之中

					}
				}

				dealAbandonService.deleteDealabandonByDocNo(param);// 根据document_no删除红废表中的记录
				// dealAbandonService.setDocStatus(param);//删除成功后将对应的票据的状态置为'已开票'
				result.put("result", 0);
				writer.print(JackJson.fromObjectToJson(result));
			}
		} catch (Exception e) {
			logger.error("Exception: ", e);
			result.put("result", "3");// 提示用户数据连接失败
			writer.print(JackJson.fromObjectToJson(result));
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/* 修改红废记录 */
	@RequestMapping(value = "/dealAbandonEdit", method = RequestMethod.POST)
	public void dealAbandonEdit(ExtPager page, HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		HashMap<String, Object> result = new HashMap<String, Object>();// 用于返回的结果集
		HashMap<String, Object> param = new HashMap<String, Object>();// 用于向后台传递参数
		User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
		try {
			if (user != null) {
				String language = (String) session.getAttribute(WebConstants.CURRENT_LANG);
				String company_id = session.getAttribute(WebConstants.CURRENT_COMPANY).toString();
				String DOCUMENT_NO = request.getParameter("DOCUMENT_NO");
				String ID = request.getParameter("VOIDED_DOC_ID");
				Integer VOIDED_DOC_ID = Integer.parseInt(ID);
				param.put("DOCUMENT_NO", DOCUMENT_NO);
				param.put("VOIDED_DOC_ID", VOIDED_DOC_ID);
				param.put("companyId", company_id);
				param.put("language", language);
				System.out.println(language);
				HashMap<String, Object> info = dealAbandonService
						.getInfoByDoc(param);// 根据单据号获得红废信息记录
				info.put("currentCpn", company_id);
				result.put("result", info);
				writer.print(JackJson.fromObjectToJson(result));
			}
		} catch (Exception e) {
			logger.error("Exception: ", e);
			result.put("result", "1");// 提示用户数据连接失败
			writer.print(JackJson.fromObjectToJson(result));
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/*
	 * 验证是否满足删除红废记录条件 条件：当进行删除操作时要先验证票据审核状态，只有是'否决'和'审核通过'的状态才可以进行删除操作
	 * 当进行删除操作时要先验证该票据状态，只有是'未开票'的状态才可以进行删除操作
	 */
	@RequestMapping(value = "/testDealAbandonDel", method = RequestMethod.POST)
	public void testDealAbandonDel(ExtPager page, HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		HashMap<String, Object> result = new HashMap<String, Object>();// 用于返回的结果集
		HashMap<String, Object> param = new HashMap<String, Object>();// 用于向后台传递参数
		User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
		try {
			if (user != null) {
				String DOCUMENT_NO = request
						.getParameter("DOCUMENT_NO");
				// param.put("DOCUMENT_NO", DOCUMENT_NO);
				param.put("companyId",
						session.getAttribute(WebConstants.CURRENT_COMPANY)
								.toString());
				String[] docsc = DOCUMENT_NO.split(",");
				// 检查审核状态
				String VOIDED_DOC_ID = request
						.getParameter("VOIDED_DOC_ID");
				String[] docs = VOIDED_DOC_ID.split(",");
				List<HashMap<String, String>> lists = new ArrayList<HashMap<String, String>>();
				HashMap<String, String> map = new HashMap<String, String>();
				for (int i = 0; i < docs.length; i++) {
					map = new HashMap<String, String>();
					map.put("id", docs[i]);
					lists.add(map);
				}

				
				String[] voids = VOIDED_DOC_ID.split(",");
				for (int i = 0; i < docs.length; i++) {
					HashMap<String, Object> checkParam = new HashMap<String, Object>();
					checkParam.put("companyId",
							session.getAttribute(WebConstants.CURRENT_COMPANY)
									.toString());
					checkParam.put("DOCUMENT_NO", docs[i]);
					checkParam.put("VOIDED_DOC_ID", voids[i]);
					checkParam
							.put("userId", Integer.parseInt(user.getUserId()));
					HashMap<String, Object> info = dealAbandonService
							.getStatusByDoc(checkParam);
					for (int j = 0; j < docsc.length; j++) {
					if (info == null || info.isEmpty()) { // 此条数据不是该用户申请编辑的
						result.put("result", "6");
						result.put("resultcode", docsc[i]);
						writer.print(JackJson.fromObjectToJson(result));
						return;
					}
					int status = Integer
							.parseInt(info.get("STATUS").toString());
					
					if (status != 0 && status != 1 && status != 2) { // 此条数据审核状态不可删除
						result.put("result", "5");
						result.put("resultcode", docsc[j]);
						writer.print(JackJson.fromObjectToJson(result));
						return;
					}
				}}

				param.put("DocList", lists);
				List<HashMap<String, Object>> listDocStatus = dealAbandonService
						.getDocStatusInfo(param);
				int flag = 0;// 标志位
				if (!listDocStatus.isEmpty() && listDocStatus != null) {
					for (HashMap<String, Object> status : listDocStatus) {
						String DOC_NO = (String) status.get("DOCUMENT_NO");
						Integer DOC_LOCKED = (Integer) status.get("DOC_LOCKED");
						// if(DOC_STATUS!=0){//提示用户存在不是'未开票'数据，无法进行删除
						// flag = 1 ;
						// result.put("result", "1");
						// result.put("resultcode", DOC_NO);
						// writer.print(JackJson.fromObjectToJson(result));
						// break;
						// }
//						if (DOC_LOCKED == 1) {// 提示用户存在'已保持'数据，无法进行删除
//							flag = 1;
//							result.put("result", "4");
//							result.put("resultcode", DOC_NO);
//							writer.print(JackJson.fromObjectToJson(result));
//							break;
//						}
					}
					if (flag == 0) {// 验证成功,满足删除条件
						result.put("result", "0");
						writer.print(JackJson.fromObjectToJson(result));
					}
				} else {// 提醒用户,没有找到数据信息
					result.put("result", "2");
					writer.print(JackJson.fromObjectToJson(result));
				}

			} else {
				writer.print("");
			}
		} catch (Exception e) {
			logger.error("Exception: ", e);
			result.put("result", "3");// 提示用户数据连接失败
			writer.print(JackJson.fromObjectToJson(result));
		} finally {
			writer.flush();
			writer.close();
		}
	}
	
	// 编辑时查看当前用户权限
	@RequestMapping(value = "/checkEditRight", method = RequestMethod.POST)
	public void checkEditRight(ExtPager page, HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");

		HashMap<String, Object> param = new HashMap<String, Object>();// 用于向后台传递参数
		String voided_doc_id = request.getParameter("voided_doc_id");
		
		param.put("companyId",session.getAttribute(WebConstants.CURRENT_COMPANY).toString());
		try {
			User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
			if (user != null) {
				param.put("voided_doc_id", voided_doc_id);
				boolean flag = false;
				ArrayList<HashMap<String, Object>> check = null;
				param.put("userId", user.getUserId());
				// 先查看当前用户的红废权限
				check = dealAbandonService.checkEditRight(param);
				int status = dealAbandonService.getAandonStatus(param);
				// 审核中和被否决状态
				if (status == 1 || status == 2 || status == 0) {
					if (check.size() > 0) {
						flag = true;
					}
				}
				writer.print(flag);
			} else {
				writer.print("");
			}
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	@RequestMapping(value = "/checkRight", method = RequestMethod.POST)
	public void checkRight(ExtPager page, HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");

		HashMap<String, Object> param = new HashMap<String, Object>();// 用于向后台传递参数
		String returnMsg = "false";

		param.put("companyId",
				session.getAttribute(WebConstants.CURRENT_COMPANY).toString());
		try {
			User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
			if (user != null) {
				param.put("userId", user.getUserId());
				int check = dealAbandonService.getCheckRights(param).size();
				if (check > 0) {
					returnMsg = "true";
				} else {
					returnMsg = "false";
				}
				writer.print(returnMsg);
			} else {
				writer.print("");
			}
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/**
	 * 验证是否满足审核红废记录条件 条件：当进行审核操作时要先验证用户权限，只有用户是该公司红废审核者才可以进行审核操作
	 * 当进行审核操作时要先验证该票据状态，只有是与当前用户红废权限相符的状态才可以进行审核操作
	 * */
	@RequestMapping(value = "/testDealAbandonCheck", method = RequestMethod.POST)
	public void testDealAbandonCheck(ExtPager page, HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		HashMap<String, Object> result = new HashMap<String, Object>();// 用于返回的结果集
		HashMap<String, Object> param = new HashMap<String, Object>();// 用于向后台传递参数
		User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
		try {
			if (user != null) {
				String DOCUMENT_NO = request
						.getParameter("DOCUMENT_NO");
				// param.put("DOCUMENT_NO", DOCUMENT_NO);
				param.put("companyId",
						session.getAttribute(WebConstants.CURRENT_COMPANY)
								.toString());
				String[] docs = DOCUMENT_NO.split(",");
				String VOIDED_DOC_ID = request
						.getParameter("VOIDED_DOC_ID");
				String[] voids = VOIDED_DOC_ID.split(",");
				param.put("userId", Integer.parseInt(user.getUserId()));
				// 得到当前用户在当前公司的红废审核者权限
				List<HashMap<String, Object>> levels = dealAbandonService
						.getCheckRights(param);
				if (levels == null || levels.isEmpty()) { // 当前用户不是该公司红废审核者
					result.put("result", "1");
					writer.print(JackJson.fromObjectToJson(result));
					return;
				}
				HashSet<Integer> roles = new HashSet<Integer>();
				for (HashMap<String, Object> level : levels) {
					roles.add(Integer.parseInt(level.get("ABANDON_ROLE")
							.toString()));
				}
				// 验证每条数据
				for (int i = 0; i < docs.length; i++) {
					HashMap<String, Object> checkParam = new HashMap<String, Object>();
					checkParam.put("companyId",
							session.getAttribute(WebConstants.CURRENT_COMPANY)
									.toString());
					checkParam.put("DOCUMENT_NO", docs[i]);
					checkParam.put("VOIDED_DOC_ID", voids[i]);
					// 得到此条数据的审核状态
					HashMap<String, Object> info = dealAbandonService
							.getStatusByDoc(checkParam);
					if (info == null || info.isEmpty()) { // 找不到这条数据
						result.put("result", "2");
						result.put("resultcode", docs[i]);
						writer.print(JackJson.fromObjectToJson(result));
						return;
					}
					int status = Integer
							.parseInt(info.get("STATUS").toString());
					if (!roles.contains(status)) { // 审核状态不正确
						result.put("result", "4");
						result.put("resultcode", docs[i]);
						writer.print(JackJson.fromObjectToJson(result));
						return;
					}
				}
				// 验证成功
				result.put("result", "0");
				writer.print(JackJson.fromObjectToJson(result));

			} else {
				writer.print("");
			}
		} catch (Exception e) {
			logger.error("Exception: ", e);
			result.put("result", "3");// 提示用户数据连接失败
			writer.print(JackJson.fromObjectToJson(result));
		} finally {
			writer.flush();
			writer.close();
		}
	}

	// 审核红废记录
	@RequestMapping(value = "/dealabandonCheck", method = RequestMethod.POST)
	public void dealabandonCheck(ExtPager page, HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		HashMap<String, Object> param = new HashMap<String, Object>();// 用于向后台传递参数
		HashMap<String, Object> result = new HashMap<String, Object>();// 用于返回的结果集
		User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
		String companyId = session.getAttribute(WebConstants.CURRENT_COMPANY).toString();
		try {
			if (user != null) {
				String VOIDED_DOC_ID = request.getParameter("VOIDED_DOC_ID");
				String[] voids = VOIDED_DOC_ID.split(",");
				String DOCUMENT_NO = request.getParameter("ids");
				String[] docs = DOCUMENT_NO.split(",");
				// 同意否决flag true为同意，false为否决
				boolean agree = (Integer.parseInt(request.getParameter("agree")) == 1);
				param.put("companyId",companyId);
				param.put("voids", voids);
				param.put("docs", docs);
				param.put("userId", Integer.parseInt(user.getUserId()));

				// 更新update_id,update_name信息 by guxiaoli
				param.put("update_name", user.getAccount());
				try {
					dealAbandonService.updateStatus(param, agree);
					result.put("result", "0");// 成功
					for (int i = 0; i < docs.length; i++) {
						HashMap<String, Object> statue = new HashMap<String, Object>();
						statue.put("company_id", companyId);
						statue.put("docNo", docs[i]);
						statue.put("invoice_id", VOIDED_DOC_ID);
						HashMap<String, Object> docStatue = dealAbandonService.getInvoiceStatus(statue);
						if ("3".equals(docStatue.get("statusNo").toString())) {
							HashMap<String, Object> execSpParam = new HashMap<String, Object>();
							execSpParam.put("docNo", docs[i]);
							execSpParam.put("userId", user.getUserId());
							execSpParam.put("companyId", session.getAttribute(WebConstants.CURRENT_COMPANY).toString());
							execSpParam.put("invoiceId", VOIDED_DOC_ID);
							execSp(execSpParam);
						}
					}
					
					/**
					 * 循环单据号发送邮件或短信
					 */
					// 取得邮件短信模板信息
					HashMap<String, Object> model2param = new HashMap<String, Object>();
					model2param.put("cpnId", companyId);
					model2param.put("type", 2);
					HashMap<String, Object> model3param = new HashMap<String, Object>();
					model3param.put("cpnId", companyId);
					model3param.put("type", 3);
					// model3 : 申请者模板
					ArrayList<HashMap<String, Object>> model2 = dealsendmsgservice.getMsgForPreview(model2param);
					// model2 : 红废审核者模板
					ArrayList<HashMap<String, Object>> model3 = dealsendmsgservice.getMsgForPreview(model3param);
					int applyerFlag = 0;
					int checkerFlag = 0;
					if (model2.size() > 0) {
						// 申请者模板启用flag
						applyerFlag = Integer.parseInt(model2.get(0).get("useFlag").toString());
					}
					if (model3.size() > 0) {
						// 审核者模板启用flag
						checkerFlag = Integer.parseInt(model2.get(0).get("useFlag").toString());
					}
					// 当审核者或申请者有一个启用时才进去循环
					if (applyerFlag == 2 || applyerFlag == 3 || checkerFlag == 2 || checkerFlag == 3) {
						for (int i = 0; i < docs.length; i++) {
							// 取得当前票据状态
							HashMap<String, Object> docStatue = new HashMap<String, Object>();
							docStatue.put("company_id", companyId);
							docStatue.put("docNo", docs[i]);
							docStatue.put("invoice_id", VOIDED_DOC_ID);
							HashMap<String, Object> statue = dealAbandonService.getInvoiceStatus(docStatue);
							// 申请者信息
							HashMap<String, Object> msgForApplicant = new HashMap<String, Object>();
							if (applyerFlag == 2 || applyerFlag == 3 ) {
								msgForApplicant = dealAbandonService.getMsgForApplicant(statue.get("userId").toString());
							}
							ArrayList<HashMap<String, Object>> checkLevel2 = new ArrayList<HashMap<String, Object>>();
							if (checkerFlag == 2 || checkerFlag == 3 ) {
								// 得到所有二级审核者
								checkLevel2 = dealAbandonService.getCheckLevel2(companyId);
							}
							// 票据当前状态
							String statueNo = statue.get("statusNo").toString();
							
							if (applyerFlag == 2 || applyerFlag == 3 ) {
								String reviewTo = model3.get(0).get("review_to").toString();;
								String reviewCc = model3.get(0).get("review_cc").toString();
								String reviewBcc = model3.get(0).get("review_bcc").toString();
								
								String applyReviewTo = model2.get(0).get("review_to").toString();
								String applyReviewCc = model2.get(0).get("review_cc").toString();
								String applyReviewBcc = model2.get(0).get("review_bcc").toString();
								
								// 当此票据被否决  发信给申请者
								if (statueNo.equals("0")) {
									try {
										sendApplyerMail(applyReviewTo, applyReviewCc, applyReviewBcc, checkLevel2, statue, model2, msgForApplicant);
									} catch (Exception e) {
										System.out.println(e);
									}
								}
								// 当此票据等待二级审核 发信给二级审核者 和申请者
								else if (statueNo.equals("2")) {
									// 发给申请者
									try {
										sendApplyerMail(applyReviewTo, applyReviewCc, applyReviewBcc, checkLevel2, statue, model2, msgForApplicant);
									} catch (Exception e) {
										System.out.println(e);
									}
									
									if (checkLevel2.size() != 0) {
										// 给审核者发邮件
										try {
											sendCheckerMail(reviewTo, reviewCc, reviewBcc, checkLevel2, statue, model3);
										} catch (Exception e) {
											System.out.println(e);
										}
									}
									
								}
								// 当此票据通过审核 发信给申请者
								else if (statueNo.equals("3")) {
									// 发给申请者
									try {
										sendApplyerMail(applyReviewTo, applyReviewCc, applyReviewBcc, checkLevel2, statue, model2, msgForApplicant);
									} catch (Exception e) {
										System.out.println(e);
									}
								}
							}
						}
					}
					/**  end*/
					writer.print(JackJson.fromObjectToJson(result));
				} catch (Exception e) {
					logger.error("Exception: ", e);
				}
			}
		} catch (Exception e) {
			logger.error("Exception: ", e);
			result.put("result", "1");// 提示用户数据连接失败
			writer.print(JackJson.fromObjectToJson(result));
		} finally {
			writer.flush();
			writer.close();
		}
	}
	
	/**
	 * 发送邮件给申请者
	 * @param applyReviewTo 	申请者模板中TO邮箱
	 * @param applyReviewCc 	申请者模板中CC邮箱
	 * @param applyReviewBcc	申请者模板中BCC邮箱
	 * @param checkLevel2		二级审核者
	 * @param statue			单据状态信息
	 * @param model2			申请者模板
	 * @param msgForApplicant	申请者信息
	 */
	private void sendApplyerMail(String applyReviewTo, String applyReviewCc, String applyReviewBcc, 
			ArrayList<HashMap<String, Object>> checkLevel2, HashMap<String, Object> statue, 
			ArrayList<HashMap<String, Object>> model2, HashMap<String, Object> msgForApplicant){
		HashMap<String, Object> getMailInfo = new HashMap<String, Object>();
		// 普通邮件初始化
		MailSenderInfo mailInfo = new MailSenderInfo();
		// gmail邮件初始化
		GmailSenderInfo gmailInfo = new GmailSenderInfo();
		// 发邮件给to
		if (applyReviewTo.contains("[收件人邮箱]")) {
			for (int j = 0; j < checkLevel2.size(); j++) {
				HashMap<String, Object> checkLevel = checkLevel2.get(j);
				getMailInfo = getMailMethord(statue, checkLevel, model2);
				String review_to = msgForApplicant.get("eMail").toString();
				if (port.equals("465")) {
					gmailInfo = (GmailSenderInfo) getMailInfo.get("mailInfo");
					sendGmail(review_to, gmailInfo);
				} else {
					mailInfo = (MailSenderInfo) getMailInfo.get("mailInfo");
					sendMail(review_to, mailInfo);
				}
			}
		} else {
			HashMap<String, Object> checkLevel = checkLevel2.get(0);
			getMailInfo = getMailMethord(statue, checkLevel, model2);
			// 收件人
			String review_to = model2.get(0).get("review_to").toString();
			
			if (port.equals("465")) {
				gmailInfo = (GmailSenderInfo) getMailInfo.get("mailInfo");
				sendGmail(review_to, gmailInfo);

				sendGmail(msgForApplicant.get("eMail").toString(), gmailInfo);
			} else {
				mailInfo = (MailSenderInfo) getMailInfo.get("mailInfo");
				sendMail(review_to, mailInfo);
				
				sendMail(msgForApplicant.get("eMail").toString(), mailInfo);
			}
		} 
		// 发邮件给cc
		if (applyReviewCc.contains("[收件人邮箱]")) {
			for (int j = 0; j < checkLevel2.size(); j++) {
				HashMap<String, Object> checkLevel = checkLevel2.get(j);
				getMailInfo = getMailMethord(statue, checkLevel, model2);

				String review_cc = msgForApplicant.get("eMail").toString();
				
				if (port.equals("465")) {
					gmailInfo = (GmailSenderInfo) getMailInfo.get("mailInfo");
					sendGmail(review_cc, gmailInfo);
				} else {
					mailInfo = (MailSenderInfo) getMailInfo.get("mailInfo");
					sendMail(review_cc, mailInfo);
				}
			}
		} else {
			HashMap<String, Object> checkLevel = checkLevel2.get(0);
			getMailInfo = getMailMethord(statue, checkLevel, model2);

			String review_cc = model2.get(0).get("review_cc").toString();
			if (port.equals("465")) {
				gmailInfo = (GmailSenderInfo) getMailInfo.get("mailInfo");
				sendGmail(review_cc, gmailInfo);
			} else {
				mailInfo = (MailSenderInfo) getMailInfo.get("mailInfo");
				sendMail(review_cc, mailInfo);
			}
		}
		// 发邮件给bcc
		if (applyReviewBcc.contains("[收件人邮箱]")) {
			for (int j = 0; j < checkLevel2.size(); j++) {
				HashMap<String, Object> checkLevel = checkLevel2.get(j);
				getMailInfo = getMailMethord(statue, checkLevel, model2);

				String review_bcc = msgForApplicant.get("eMail").toString();
				
				if (port.equals("465")) {
					gmailInfo = (GmailSenderInfo) getMailInfo.get("mailInfo");
					sendGmail(review_bcc, gmailInfo);
				} else {
					mailInfo = (MailSenderInfo) getMailInfo.get("mailInfo");
					sendMail(review_bcc, mailInfo);
				}
			}
		} else {
			HashMap<String, Object> checkLevel = checkLevel2.get(0);
			getMailInfo = getMailMethord(statue, checkLevel, model2);
			
			String review_bcc = model2.get(0).get("review_bcc").toString();
			
			if (port.equals("465")) {
				gmailInfo = (GmailSenderInfo) getMailInfo.get("mailInfo");
				sendGmail(review_bcc, gmailInfo);
			} else {
				mailInfo = (MailSenderInfo) getMailInfo.get("mailInfo");
				sendMail(review_bcc, mailInfo);
			}
		}
	}
	
	/**
	 * 给审核者发邮件
	 * @param applyReviewTo		申请者模板中TO邮箱
	 * @param applyReviewCc		申请者模板中CC邮箱
	 * @param applyReviewBcc	申请者模板中BCC邮箱
	 * @param checkLevel2		审核者信息
	 * @param statue			单据信息
	 * @param model3			审核者模板
	 */
	private void sendCheckerMail(String applyReviewTo, String applyReviewCc, String applyReviewBcc, 
			ArrayList<HashMap<String, Object>> checkLevel2, HashMap<String, Object> statue, ArrayList<HashMap<String, Object>> model3){
		HashMap<String, Object> getMailInfo = new HashMap<String, Object>();
		MailSenderInfo mailInfo = new MailSenderInfo();
		GmailSenderInfo gmailInfo = new GmailSenderInfo();
		// 发邮件给to
		if (applyReviewTo.contains("[收件人邮箱]")) {
			for (int j = 0; j < checkLevel2.size(); j++) {
				HashMap<String, Object> checkLevel = checkLevel2.get(j);
				getMailInfo = getMailMethord(statue, checkLevel, model3);
				
				String review_to = checkLevel.get("eMail").toString();
				
				if (port.equals("465")) {
					gmailInfo = (GmailSenderInfo) getMailInfo.get("mailInfo");
					sendGmail(review_to, gmailInfo);
				} else {
					mailInfo = (MailSenderInfo) getMailInfo.get("mailInfo");
					sendMail(review_to, mailInfo);
				}
			}
		} else {
			HashMap<String, Object> checkLevel = checkLevel2.get(0);
			getMailInfo = getMailMethord(statue, checkLevel, model3);

			String review_to = model3.get(0).get("review_to").toString();
			if (port.equals("465")) {
				gmailInfo = (GmailSenderInfo) getMailInfo.get("mailInfo");
				sendGmail(review_to, gmailInfo);
			} else {
				mailInfo = (MailSenderInfo) getMailInfo.get("mailInfo");
				sendMail(review_to, mailInfo);
			}
		} 
		// 发邮件给cc
		if (applyReviewCc.contains("[收件人邮箱]")) {
			for (int j = 0; j < checkLevel2.size(); j++) {
				HashMap<String, Object> checkLevel = checkLevel2.get(j);
				getMailInfo = getMailMethord(statue, checkLevel, model3);

				String review_cc = checkLevel.get("eMail").toString();
				if (port.equals("465")) {
					gmailInfo = (GmailSenderInfo) getMailInfo.get("mailInfo");
					sendGmail(review_cc, gmailInfo);
				} else {
					mailInfo = (MailSenderInfo) getMailInfo.get("mailInfo");
					sendMail(review_cc, mailInfo);
				}
			}
		} else {
			HashMap<String, Object> checkLevel = checkLevel2.get(0);
			getMailInfo = getMailMethord(statue, checkLevel, model3);

			String review_cc = model3.get(0).get("review_cc").toString();
			if (port.equals("465")) {
				gmailInfo = (GmailSenderInfo) getMailInfo.get("mailInfo");
				sendGmail(review_cc, gmailInfo);
			} else {
				mailInfo = (MailSenderInfo) getMailInfo.get("mailInfo");
				sendMail(review_cc, mailInfo);
			}
		}
		// 发邮件给bcc
		if (applyReviewBcc.contains("[收件人邮箱]")) {
			for (int j = 0; j < checkLevel2.size(); j++) {
				HashMap<String, Object> checkLevel = checkLevel2.get(j);
				getMailInfo = getMailMethord(statue, checkLevel, model3);

				String review_bcc = checkLevel.get("eMail").toString();
				if (port.equals("465")) {
					gmailInfo = (GmailSenderInfo) getMailInfo.get("mailInfo");
					sendGmail(review_bcc, gmailInfo);
				} else {
					mailInfo = (MailSenderInfo) getMailInfo.get("mailInfo");
					sendMail(review_bcc, mailInfo);
				}
			}
		} else {
			HashMap<String, Object> checkLevel = checkLevel2.get(0);
			getMailInfo = getMailMethord(statue, checkLevel, model3);

			String review_bcc = model3.get(0).get("review_bcc").toString();
			if (port.equals("465")) {
				gmailInfo = (GmailSenderInfo) getMailInfo.get("mailInfo");
				sendGmail(review_bcc, gmailInfo);
			} else {
				mailInfo = (MailSenderInfo) getMailInfo.get("mailInfo");
				sendMail(review_bcc, mailInfo);
			}
		}
	}
	/**
	 * @param statue 包含所有收件人信息
	 * @param type 发信给不同角色的模板flag
	 * 				1：为寄送通知模板
	 * 				2：为红废申请者模板
	 * 				3：为红废审核者模板
	 */
	private HashMap<String, Object> getMailMethord(HashMap<String, Object> statue, HashMap<String, Object> checkLevel, ArrayList<HashMap<String, Object>> model){
		HashMap<String, Object> result = new HashMap<String, Object>();
		
		// 模板取值--------------------
		String review_to = null;
		String review_cc = null;
		String review_bcc = null;
		String review_subject = null;
		String review_email = null;
		String eMail = null;
		String fullName = null;
		// 数据取值-------------------
		String docNo = null;
		String companyName = null;
		String invoiceNoBegin = null;
		String invoiceNoEnd = null;
		String returnDate = null;
		String voidFlag = null;
		String invoiceNo = null;
		String invoiceDate = null;
		String invoiceCode = null;
		boolean flag = false;
		
		try {
			// 收件人
			review_to = model.get(0).get("review_to").toString();
			review_cc = model.get(0).get("review_cc").toString();
			review_bcc = model.get(0).get("review_bcc").toString();
			// 邮件主题
			review_subject = model.get(0).get("review_subject").toString();
			// 邮件内容
			review_email = model.get(0).get("review_email").toString();
			flag = true;
		} catch (Exception e) {
			System.out.println(e);
			return null;
		}
		if (flag) {
			// 邮件服务器地址
			String host = Const.PROPERTIES.getProperty("mailserverhost");
			// 邮件服务器端口
			port = Const.PROPERTIES.getProperty("mailserverport");
			// 邮箱用户名
			String username = Const.PROPERTIES.getProperty("mailusername");
			// 邮箱密码
			String password = Const.PROPERTIES.getProperty("mailpassword");
			
			boolean dflag = false;
			try {
				// 数据取值-------------------
				docNo = statue.get("docNo").toString();
				// 公司名称
				companyName = statue.get("companyName").toString();
				// 原发票开始号
				invoiceNoBegin = statue.get("invoiceNoBegin").toString();
				// 原发票结束号
				invoiceNoEnd = statue.get("invoiceNoEnd").toString();
				// 退回日期
				returnDate = statue.get("returnDate").toString();
				// 标记状态
				voidFlag = statue.get("voidFlag").toString();
				// 原发票代码
				invoiceNo = statue.get("invoiceNo").toString();
				invoiceDate = statue.get("invoiceDate").toString();
				invoiceCode = statue.get("invoiceCode").toString();
				// 审核状态
				// String status = statue.get("status").toString();
				// String userId = null;
				// String firstUser = statue.get("firstUser").toString();
				// String firstTime = statue.get("firstTime").toString();
				// String secondUser = null;
				// String secondTime = null;
				// String abandonRole = null;
			
				// String userName = null;
				if (checkLevel != null) {
					eMail = checkLevel.get("eMail").toString();
					fullName = checkLevel.get("fullName").toString();
				} else {
					eMail = review_to;
					fullName = "";
				}
				dflag = true;
			} catch (Exception e) {
				System.out.println(e);
				return null;
			}
			
			if (dflag) {
				Date date = new Date();
				java.text.DateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
				String datetime = format.format(date);
				// [原发票代码][原发票开始号][原发票结束号][退回日期][标记状态][红冲号码][红冲日期][单据号][日期][公司名称][收件人名称][收件人邮箱]
				// 替换--------------------
				// to
				if(review_to.contains("[收件人邮箱]")){
					review_to = review_to.replace("[收件人邮箱]", eMail);
				}
				// cc
				if(review_cc.contains("[收件人邮箱]")){
					review_cc = review_cc.replace("[收件人邮箱]", eMail);
				}
				// bcc
				if(review_bcc.contains("[收件人邮箱]")){
					review_bcc = review_bcc.replace("[收件人邮箱]", eMail);
				}
				// subject
				if(review_subject.contains("[公司名称]")){
					review_subject = review_subject.replace("[公司名称]", companyName);
				}
				if(review_subject.contains("[原发票代码]")){
					review_subject = review_subject.replace("[原发票代码]", invoiceNo);
				}
				if(review_subject.contains("[日期]")){
					review_subject = review_subject.replace("[日期]", datetime);
				}
				// mail
				if(review_email.contains("[收件人名称]")){
					review_email = review_email.replace("[收件人名称]", fullName);
				}
				if(review_email.contains("[公司名称]")){
					review_email = review_email.replace("[公司名称]", companyName);
				}
				if(review_email.contains("[原发票代码]")){
					review_email = review_email.replace("[原发票代码]", invoiceCode);
				}
				if(review_email.contains("[原发票开始号]")){
					review_email = review_email.replace("[原发票开始号]", invoiceNoBegin);
				}
				if(review_email.contains("[原发票结束号]")){
					review_email = review_email.replace("[原发票结束号]", invoiceNoEnd);
				}
				if(review_email.contains("[退回日期]")){
					review_email = review_email.replace("[退回日期]", returnDate);
				}
				if(review_email.contains("[标记状态]")){
					review_email = review_email.replace("[标记状态]", voidFlag);
				}
				if(review_email.contains("[红冲号码]")){
					review_email = review_email.replace("[红冲号码]", invoiceNo);
				}
				if(review_email.contains("[红冲日期]")){
					review_email = review_email.replace("[红冲日期]", invoiceDate);
				}
				if(review_email.contains("[单据号]")){
					review_email = review_email.replace("[单据号]", docNo);
				}
				if(review_email.contains("[日期]")){
					review_email = review_email.replace("[日期]", datetime);
				}
				
				MailSenderInfo mailInfo = new MailSenderInfo();
				GmailSenderInfo gmail = new GmailSenderInfo();
				
				if (port.equals("465")) {
					gmail.setContent(review_email);
					gmail.setHost(host);
					gmail.setPassword(password);
					gmail.setPort(port);
					gmail.setSubject(review_subject);
					gmail.setUsername(username);
					
					result.put("mailInfo", gmail);
				} else {
					// 邮件设置
					mailInfo.setMailServerHost(host);
					mailInfo.setMailServerPort(port);
					mailInfo.setValidate(true);
					mailInfo.setUserName(username);
					mailInfo.setPassword(password);
					mailInfo.setFromAddress(username);
					mailInfo.setSubject(review_subject);
					mailInfo.setContent(review_email);
					
					result.put("mailInfo", mailInfo);
				}
			}
		}
		return result;
	}
	// 普通邮件发送
	private void sendMail(String review_cc, MailSenderInfo mailInfo){
		try {
			SimpleMailSender sms = new SimpleMailSender();
			if (!Tools.isEmpty(review_cc)) {
				String[] reviewCcList = review_cc.split(";");
				for (int i = 0; i < reviewCcList.length; i++) {
					mailInfo.setToAddress(reviewCcList[i]);
					sms = new SimpleMailSender();
					sms.sendTextMail(mailInfo);
				}
			}
		} catch (Exception e) {
			System.out.println(e);
		}
	}
	// gmail邮件发送
	private void sendGmail(String review_cc, GmailSenderInfo mailInfo){
		try {
			GmailSender gmailsender = new GmailSender();
			if (!Tools.isEmpty(review_cc)) {
				String[] reviewCcList = review_cc.split(";");
				for (int i = 0; i < reviewCcList.length; i++) {
					mailInfo.setMailTo(reviewCcList[i]);
					gmailsender.mailsend(mailInfo);
				}
			}
		} catch (Exception e) {
			System.out.println(e);
		}
	}
	
	// 获取红废类型
	@RequestMapping(value = "/getAbandonType")
	public void getAbandonType(ExtPager page, HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		
		try {
			String lang = session.getAttribute(WebConstants.CURRENT_LANG).toString();
			HashMap<String, Object> param = new HashMap<String, Object>();
			param.put("lang", lang);
			List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
			ArrayList<HashMap<String, Object>> result = dealAbandonService.getAbandonType(param);
			HashMap<String, String> map = new HashMap<String, String>();
			if(lang.equals("en")){
			    map.put("text", "All"); 
			}else{
				map.put("text", "所有");
			}
			map.put("value", "0");
			list.add(map);
			for (int i = 0; i < result.size(); i++) {
				HashMap<String, String> map1 = new HashMap<String, String>();
				map1.put("text", (String) result.get(i).get("text"));
				map1.put("value",  result.get(i).get("value").toString());
				list.add(map1);
			}
			String returnMsg = JackJson.fromObjectToJson(list);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}
	
	private void execSp(HashMap<String, Object> param) {
		// 获取刚插入数据的VOIDED_DOC_ID
		int VOIDED_DOC_ID =Integer.parseInt(param.get("invoiceId").toString()) ;
		// 调用存储过程接返回值
		String companyId = (String) param.get("companyId");
		String userId = (String) param.get("userId");
		Connection conn = null;
		try {
			CallableStatement proc = null;
			conn = jdbcTemplate.getDataSource().getConnection();
			// 调用存储过程
			proc = conn.prepareCall("{ call sp_tax_abandon(?,?,?,?) }");
			// 传入第一个参数 公司ID
			proc.setInt(1, Integer.parseInt(companyId));
			// 传入第二个参数 用户ID
			proc.setInt(2, Integer.parseInt(userId));
			// 传入第一个参数 红废单据ID
			proc.setInt(3, VOIDED_DOC_ID);
			// 注册输出参数
			proc.registerOutParameter(4, Types.INTEGER);
			proc.execute();
			// 接收存储过程返回值
			int result = proc.getInt(4);
			// 如果存储过程返回的返回值为0
			if (result == 0) {
				// 更改票据状态
				dealAbandonService.updateBaseOnSp(param);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	/*
	 * 获取红废处理，一般查询单据列表信息
	 */
	@RequestMapping(value = "/getDealAbandonNo")
	public void getDealAbandonNo(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		try {
			String companyId = session.getAttribute(WebConstants.CURRENT_COMPANY).toString();
			HashMap<String, Object> param = new HashMap<String, Object>();
			param.put("companyId", companyId);
			ArrayList<HashMap<String, Object>> result = dealAbandonService.getAbandonNo(param);
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}
	
	/*
	 * 获取红废处理，一般查询客户列表信息
	 */
	@RequestMapping(value = "/getDealAbandonCust")
	public void getDealAbandonCust(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		try {
			String companyId = session.getAttribute(WebConstants.CURRENT_COMPANY).toString();
			HashMap<String, Object> param = new HashMap<String, Object>();
			param.put("companyId", companyId);
			ArrayList<HashMap<String, Object>> result = dealAbandonService.getDealAbandonCust(param);
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}
	//获取红废处理查询原发票开始号下拉框
	@RequestMapping(value = "/getInvoiceNumBegin")
	public void getInvoiceNumBegin(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		try {
			String companyId = session.getAttribute(WebConstants.CURRENT_COMPANY).toString();
			User user=(User) session.getAttribute(WebConstants.CURRENT_USER);
			HashMap<String, Object> param = new HashMap<String, Object>();
			if(user!=null){
				param.put("userId", Integer.parseInt(user.getUserId()));
			}
			param.put("companyId", companyId);
			ArrayList<HashMap<String, Object>> result = dealAbandonService
					.getInvoiceNumBegin(param);
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}
	
	
	//获取红废处理查询原发票开始号下拉框
	@RequestMapping(value = "/getInvoiceNumEnd")
	public void getInvoiceNumEnd(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		try {
			String companyId = session.getAttribute(WebConstants.CURRENT_COMPANY).toString();
			User user=(User) session.getAttribute(WebConstants.CURRENT_USER);
			HashMap<String, Object> param = new HashMap<String, Object>();
			if(user!=null){
				param.put("userId", Integer.parseInt(user.getUserId()));
			}
			param.put("companyId", companyId);
			ArrayList<HashMap<String, Object>> result = dealAbandonService
					.getInvoiceNumEnd(param);
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}
	
	//获取红废处理查询原发票代码下拉框
		@RequestMapping(value = "/getInvoiceCodetoAbandon")
		public void getInvoiceCode(HttpSession session, HttpServletRequest request,
				HttpServletResponse response, PrintWriter writer) {
			response.setContentType("text/plain;charset=UTF-8");
			try {
				String companyId = session.getAttribute(WebConstants.CURRENT_COMPANY).toString();
				User user=(User) session.getAttribute(WebConstants.CURRENT_USER);
				HashMap<String, Object> param = new HashMap<String, Object>();
				if(user!=null){
					param.put("userId", Integer.parseInt(user.getUserId()));
				}
				param.put("companyId", companyId);
				ArrayList<HashMap<String, Object>> result = dealAbandonService
						.getInvoiceCodetoAbandon(param);
				String returnMsg = JackJson.fromObjectToJson(result);
				logger.debug("{}", returnMsg);
				writer.print(returnMsg);
			} catch (Exception e) {
				logger.error("Exception: ", e);
			} finally {
				writer.flush();
				writer.close();
			}
		}
}